package com.mgq.juc.c1;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author MaGuangQi
 * 测试CyclicBarrier, 作用和countdownlatch类似,
 * 但是CyclicBarrier的await()方法,减为0时,就会进行重置.
 * 例子是循环3次,分别执行任务1,任务2.每次都是等待2个任务运行结束
 * @date 2021-12-24 11:02
 **/
@Slf4j
public class TestCyclicBarrier {

    public static void main(String[] args) {
        //注意:线程池中线程的个数应该和cyclicBarrier构造方法中的值相等
        ExecutorService executorService = Executors.newFixedThreadPool(2);

        CyclicBarrier cyclicBarrier=new CyclicBarrier(2,()->{
            log.debug("task1,task2 end");
        });
        for (int i = 0; i < 3; i++) {
            executorService.submit(()->{

                try {
                    log.debug("task1 begging");
                    Thread.sleep(1000);
                    cyclicBarrier.await();
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }
            });
            executorService.submit(()->{

                try {
                    log.debug("task2 begging");
                    Thread.sleep(2000);
                    cyclicBarrier.await();
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }
            });
        }

        executorService.shutdown();
    }

}
